package com.econage.eccm.test.base.webdatasource.web;

import com.econage.eccm.test.base.mybatis.support.MybatisWebContext;

import javax.servlet.*;
import java.io.IOException;

public class AppDataSourceFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        DbTransaction.checkAppDataSource();//连接池
        MybatisWebContext.checkSqlSessionTemplate();//mybatis环境
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long dbActionId = 0;
        try {
            if(DbTransaction.getDbActionUid()==0){
                dbActionId = DbTransaction.register4Access();
            }
            chain.doFilter(request, response);
        }finally{
            if(dbActionId!=0){
                try{ MybatisWebContext.close(); }catch(Exception ignore){}
                try{ DbTransaction.closeForce(dbActionId); }catch(Exception ignore){}
            }
        }
    }

    @Override
    public void destroy() {

    }
}
